#include"fractor.h"
#include"tool.h"
#include<stdio.h>
void init(FRACTOR *f) {
	f->up = 1;
	f->down = 1;
}
void print(FRACTOR *f) {
	if (f->up == 0)
		puts("0");
	else if (f->down == 1)
		printf("%d\n", f->up);
	else
		printf("%d/%d\n", f->up, f->down);
}

void setUp(FRACTOR *f, int newUp) {
	setUpDown(f, newUp, f->down);
}
void setDown(FRACTOR *f, int newDown) {
	setUpDown(f, f->up, newDown);
}
void simplify(FRACTOR *f) {
	int g = gcd(ABS(f->up), ABS(f->down));
	f->up /= g;
	f->down /= g;
	if (f->up < 0 || f->down < 0) {
		if (f->up * f->down < 0) {
			f->up = -ABS(f->up);
			f->down = ABS(f->down);
		} else {
			f->up = ABS(f->up);
			f->down = ABS(f->down);

		}
	}

}
void setUpDown(FRACTOR *f, int up, int down) {
	f->up = up;
	f->down = down;
	simplify(f);
}
void setMinus(FRACTOR *f) {
	setUp(f, -f->up);
}
void setReverse(FRACTOR *f) {
	setUpDown(f, f->down, f->up);

}

void add(FRACTOR *a, FRACTOR *b, FRACTOR*c) {
	int up = a->up * b->down + a->down * b->up;
	int down = a->down * b->down;
	c->up = up;
	c->down = down;
	simplify(c);

}
void sub(FRACTOR *a, FRACTOR *b, FRACTOR*c) {
    FRACTOR br;
	setUpDown(&br,b->up,b->down);
	setMinus(&br);
	add(a, &br, c);

	simplify(c);

}
void mul(FRACTOR *a, FRACTOR *b, FRACTOR*c) {
	int up = a->up * b->up;
	int down = a->down * b->down;
	c->up = up;
	c->down = down;
	simplify(c);

}
void div(FRACTOR *a, FRACTOR *b, FRACTOR*c) {
	FRACTOR br;
	setUpDown(&br,b->up,b->down);
	setReverse(&br);
	mul(a, &br, c);
	simplify(c);

}
int cmp(const FRACTOR* a, const FRACTOR *b) {
	FRACTOR c;
	sub(a, b, &c);
	return c.up;
}
